package demo.swing.administrator;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import org.postgresql.util.PSQLException;

import demo.swing.SqlQuery;
import demo.swing.administrator.panel.AdministratorPanel;

public class EnterAdministrator extends JFrame implements ActionListener {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1980679353174666038L;
	public static String OLD_NAME = null;
	private JLabel passwordLabel;
	private JLabel loginLabel;
	private JTextField loginTextField;
	private JPasswordField passwordField;
	private JButton okBtn;
	private AdministratorPanel administratorPanel = null;
	
	public AdministratorPanel getAdministratorPanel() {
		return administratorPanel;
	}

	public JLabel getPasswordLabel(){
		return passwordLabel;
	}

	public JLabel getLoginLabel() {
		return loginLabel;
	}

	public JTextField getLoginTextField() {
		return loginTextField;
	}

	public JPasswordField getPasswordField() {
		return passwordField;
	}

	public EnterAdministrator(String title){
		super(title);
		passwordLabel = new JLabel("Enter the a password of administrator:");
		loginLabel = new JLabel("Enter the a user with administrators privilegies");
		if (EnterAdministrator.OLD_NAME != null){
			loginTextField = new JTextField(EnterAdministrator.OLD_NAME);
		}else{
			loginTextField = new JTextField("Someuser");
		}
		passwordField = new JPasswordField();
		okBtn = new JButton("Ok");
		okBtn.addActionListener(this);
		this.setLayout(new GridLayout(3, 2));
		this.add(loginLabel);
		this.add(loginTextField);
		this.add(passwordLabel);
		this.add(passwordField);
		this.add(okBtn);
		this.pack();
		this.setVisible(true);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		OLD_NAME = new String(getLoginTextField().getText());
		SqlQuery sql = null;
		try {
			sql = new SqlQuery("192.168.1.4", "5432", getLoginTextField().getText(), new String(getPasswordField().getPassword()));
			setVisible(false);
			administratorPanel = new AdministratorPanel(getLoginTextField().getText(), new String(getPasswordField().getPassword()), sql);
		} catch (PSQLException e1) {
			// TODO: handle exception
			JOptionPane.showConfirmDialog(this, "Invalid password.", "Authentication is not passed", JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE, null);
		} catch(Exception e2){
			e2.printStackTrace();
		}
	}

}
